package org.fatmansoft.teach.service;

import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.*;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class AbsenceRecordService {
    @Autowired
    AbsenceRecordRepository absenceRecordRepository;
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    CourseRepository courseRepository;
    @Autowired
    TeacherRepository teacherRepository;
    @Autowired
    PersonRepository personRepository;
    @Autowired
    UserRepository userRepository;

    /*********************************************辅助方法***********************************************/

    //主键自增
    public synchronized Integer getNewAbsenceRecordId(){
        Integer  id =absenceRecordRepository.getMaxId();  // 查询最大的id
        if(id == null){
            id = 1;
        } else{
            id = id+1;
        }
        return id;
    }

    public Student getStudentByPersonName(String personName){
        Optional<Person> person = personRepository.findByNum(personName);
        if(person.isPresent()){ //如果存在这个person
            Person p =person.get();
            Optional<Student> student = studentRepository.findByPersonPersonId(p.getPersonId());
            if(student.isPresent()){    //如果这个person是学生，返回学生
                return student.get();
            }
        }
        return null;
    }
    public Teacher getLoginTeacher() {
        Integer userId = CommonMethod.getUserId();
        Teacher teacher = null;
        User user = getUser(userId);
        if(user != null) {
            Integer personId = user.getPerson().getPersonId();
            teacher = getTeacherByPersonId(personId);
        }
        return teacher;
    }
    public User getUser(Integer id) {
        User user = null;
        if(id != null) {
            Optional<User> x = userRepository.findById(id);
            if(x.isPresent()) {
                user = x.get();
            }
        }
        return user;
    }
    public Teacher getTeacherByPersonId(Integer id) {
        Teacher teacher = null;
        if(id != null) {
            Optional<Teacher> x = teacherRepository.findByPersonPersonId(id);
            if(x.isPresent()) {
                teacher = x.get();
            }
        }
        return teacher;
    }
    /**********************************************接口业务代码**************************************************/
    //【查】可选参数：学生/教师账、起始日期、结束日期、课程id
    public DataResponse getAbsenceRecordListByPersonNum(DataRequest dataRequest){
        String num = dataRequest.getString("username");
        String sd = dataRequest.getString("startDate");
        String ed = dataRequest.getString("endDate");
        Integer cd = dataRequest.getInteger("courseId");
        Optional<Person> p = personRepository.findByNum(num);
        if (p.isEmpty()) {    //查无此人
            return CommonMethod.getReturnMessageError("查无此人");
        }
        Person person = p.get();
        List datalist = null;
        if(person.getType().equals("2")){  //教师
            Optional<Teacher> t = teacherRepository.findByPersonPersonId(person.getPersonId());
            Teacher teacher = t.get();
            String stuNum = dataRequest.getString("studentNum");
            if(stuNum!=null){
                Optional<Student> s = studentRepository.findByPersonNum(stuNum);
                if(s.isEmpty()){
                    return CommonMethod.getReturnMessageError("未能找到该学号对应的学生");
                }
                Student student = s.get();
                datalist = getAbsenceRecordMapList(teacher.getTeacherId(),student.getStudentId(), sd, ed, cd);
            }
            else {
                datalist = getAbsenceRecordMapList(teacher.getTeacherId(),null, sd, ed, cd);
            }
        } else if (person.getType().equals("1")) {  //学生
            Optional<Student> s = studentRepository.findByPersonPersonId(person.getPersonId());
            Student student = s.get();
            String tecNum = dataRequest.getString("teacherNum");
            if(tecNum!=null){
                Optional<Teacher> t = Optional.ofNullable(teacherRepository.findByPersonNum(tecNum));
                if(t.isEmpty()){
                    return CommonMethod.getReturnMessageError("未能找到该账号对应的老师");
                }
                Teacher teacher = t.get();
                datalist = getAbsenceRecordMapList(teacher.getTeacherId(),student.getStudentId(), sd, ed, cd);
            }
            else {
                datalist = getAbsenceRecordMapList(null,student.getStudentId(), sd, ed, cd);
            }
        }
        return CommonMethod.getReturnData(datalist);
    }
    private List getAbsenceRecordMapList(Integer teacherId,Integer studentId,String startDate,String endDate,Integer courseId) {
        List dataList = new ArrayList();
        List<AbsenceRecord> AbsenceRecordList = null;
        System.out.println(courseId);
        //无论是教师还是学生，都用同一个查询方法。
        AbsenceRecordList = absenceRecordRepository.findByTeacherIdAndStudentIdAndDateStringBetweenAndCourseId(teacherId,studentId,startDate,endDate,courseId);
        if(AbsenceRecordList == null || AbsenceRecordList.isEmpty()) {
            return dataList;
        }
        for (AbsenceRecord abr : AbsenceRecordList) {
            dataList.add(getMapFromLogList(abr));
        }
        return dataList;
    }
    public Map getMapFromLogList(AbsenceRecord abr) {
        Map m = new HashMap();
        if(abr == null) {
            return m;
        }
        m.put("date",abr.getDate());
        m.put("courseName",abr.getCourse().getName());
        m.put("courseId",abr.getCourse().getCourseId());
        m.put("teacherName",abr.getCourse().getTeacher().getPerson().getName());
        m.put("teacherId",abr.getCourse().getTeacher().getTeacherId());
        m.put("studentId",abr.getStudent().getStudentId());
        m.put("studentName",abr.getStudent().getPerson().getName());
        m.put("studentNum",abr.getStudent().getPerson().getNum());
        m.put("absenceRecordId",abr.getAbsenceRecordId());
        return m;
    }

    //【改】根据AbsenceRecordId，此方法只有教师能用。教师可以修改缺勤日期、学生姓名、课程（范围是自己教的内容）
    public DataResponse editRecordById(DataRequest dataRequest) {
        //根据studentLogId编辑日志内容
        Integer absenceRecordId = dataRequest.getInteger("absenceRecordId");
        Map form = dataRequest.getMap("form"); //参数获取Map对象。内含log各个新信息

        AbsenceRecord record= absenceRecordRepository.getById(absenceRecordId);
        record.setCourse(courseRepository.getById(Objects.requireNonNull(CommonMethod.getInteger(form, "courseId"))));
        record.setDate(CommonMethod.getString(form,"date"));

        absenceRecordRepository.save(record);  // 修改保存
        return CommonMethod.getReturnData(record.getAbsenceRecordId());  // 将recordId返回前端
    }
    //【删】根据StudentLogId删除日志内容
    @Transactional
    public DataResponse deleteRecordById(DataRequest dataRequest){
        Integer studentLogId = dataRequest.getInteger("absenceRecordId");
        absenceRecordRepository.deleteByAbsenceRecordId(studentLogId);
        return CommonMethod.getReturnMessageOK();
    }
    //【增】参数：学生学号、课程id、日期
    public DataResponse createRecord(DataRequest dataRequest) {
        Teacher teacher = getLoginTeacher();
        Student s =getStudentByPersonName(dataRequest.getString("studentNum"));
        if(s==null){    //查无此人
            return CommonMethod.getReturnMessageError("未能找到该学号对应的学生");
        }
        Map form = dataRequest.getMap("form");
        System.out.println("form:"+form);
        Integer courseId = CommonMethod.getInteger(form,"courseId");
        Set<Course> courses = s.getCourses();
        if (courseId != null) {
            Course thisCourse = courseRepository.getById(courseId);
            if (!courses.contains(thisCourse)) {
                return CommonMethod.getReturnMessageError("学生没选择此课程！");
            }
        }
        AbsenceRecord absenceRecord = new AbsenceRecord();
        absenceRecord.setAbsenceRecordId(getNewAbsenceRecordId());
        absenceRecord.setStudent(s);
        absenceRecord.setTeacher(teacher);
        absenceRecord.setDate(CommonMethod.getString(form,"date"));
        absenceRecord.setCourse(courseRepository.getById(courseId));

        absenceRecordRepository.saveAndFlush(absenceRecord);
        return CommonMethod.getReturnData(absenceRecord.getAbsenceRecordId());  // 将absenceRecordId返回前端
    }
}
